<?php
namespace app\modules\controllers;
use Yii;
use yii\web\Controller;
use app\models\Product;
use app\models\Category;
use yii\web\UploadedFile;
use app\models\UploadForm;
use yii\data\Pagination;
use Qiniu\Auth;//// 引入鉴权类
use Qiniu\Storage\UploadManager;
require '../vendor/autoload.php';
//use Qiniu\Storage\UploadManager;

class ProductController extends Controller
{
    //商品列表
    public function actionList()
    {
        $this->layout='adminlist.php';
        $model= Product::find();
        $count=$model->count();
        $pageSize= Yii::$app->params['pageSize']['product'];
        $page=new Pagination(['totalCount'=>$count,'pageSize'=>$pageSize]);
        $products=$model->offset($page->offset)->limit($page->limit)->all();
        return $this->render('products',['products'=>$products,'pager'=>$page]);
    }
    //商品添加
    public function actionAdd()
    {
        $this->layout='adminlist.php';
        $model=new Product();
        $cate=new Category;
        $list=$cate->getOptions();
        unset($list[0]);//去除第一个
        if(Yii::$app->request->isPost){
            $post= Yii::$app->request->post();
            $pics= $this->upload();
            if(!$pics){
            $model->addError('cover','封面不能为空');
            }else{
                $post['Product']['cover']=$pics['cover'];
                $post['Product']['pics']=$pics['pics'];
            }
            if($pics && $model->add($post)){
                Yii::$app->session->setFlash('info','添加成功');
            }else{
                Yii::$app->session->setFlash('info','添加失败');
            }
        }
       
        return $this->render('add',['model'=>$model,'opts'=>$list]);
    }
    
    private function upload()
    {
        if($_FILES['Product']['error']['cover']>0){
            return false;
        }
        $auth=new Auth(Product::AK, Product::SK);//// 构建鉴权对象
        $token = $auth->uploadToken(Product::BUCKET);//// 生成上传 Token,要上传的空间Product::BUCKET
        $filePath = $_FILES['Product']['tmp_name']['cover'];//// 要上传文件的本地路径
        $key = uniqid().'.jpg';// 上传到七牛后保存的文件名
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            Yii::$app->session->setFlash('info','上传失败');
        } else {
            Yii::$app->session->setFlash('info','上传成功');
        }
        //拼接图片链接
        $cover='http://'.Product::DOMAIN.'/'.$key;
        $pics=[];
        foreach ($_FILES['Product']['tmp_name']['pics'] as $k=>$file){
            if($_FILES['Product']['tmp_name']['pics'][$k]>0){
                continue;//如果有错，则退出此循环，进入下一个循环
            }
            $key= uniqid().'.jpg';
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
            if ($err !== null) {
                Yii::$app->session->setFlash('info','上传失败');
            } else {
                Yii::$app->session->setFlash('info','上传成功');
            }
            $pics[$key]='http://'.Product::DOMAIN.'/'.$key;
        }
        return ['cover'=>$cover,'pics'=> json_encode($pics)];
//        $accessKey = Product::AK;
//        $secretKey = Product::SK;
//        $auth = new Auth($accessKey, $secretKey);
//        //baseUrl构造成私有空间的域名/key的形式
//        $baseUrl = 'ojc7pl2ko.bkt.clouddn.com';
//        $authUrl = $auth->privateDownloadUrl($baseUrl);
//        echo $authUrl;exit;

        
//        $qiniu = new \Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET);
//        $qiniu=new Auth(Product::AK, Product::SK);
//        $key = time();
////        $upToken = $qiniu->uploadToken($bucket);
//        
//        $qiniu->uploadFile($_FILES['Product']['tmp_name']['cover'],$key);//上传临时文件
//        $cover = $qiniu->getLink($key);//获取外链,相当于封面图片存储连接
//        $pics=[];
//        foreach ($_FILES['Product']['tmp_name']['pics'] as $k=>$file){
//            if($_FILES['Product']['tmp_name']['pics'][$k]>0){
//                continue;//如果有错，则退出此循环，进入下一个循环
//            }
//            $key= uniqid();
//            $qiniu->uploadFile($file, $key);
//            $pics[$key]=$qiniu->getLink($key);
//        }
//        return ['cover'=>$cover,'pics'=> json_encode($pics)];
    }
    
    //商品修改
    public function actionMod()
    {
        $this->layout='adminlist.php';
        $cate=new Category;
        $list=$cate->getOptions();
        array_shift($list);
        $productid= Yii::$app->request->get('productid');
        $model= Product::find()->where('productid=:pid',[':pid'=>$productid])->one();
        if(Yii::$app->request->isPost){
            $post= Yii::$app->request->post();
            $auth=new Auth(Product::AK, Product::SK);
            $token = $auth->uploadToken(Product::BUCKET);
            $filePath = $_FILES['Product']['tmp_name']['cover'];
            $post['Product']['cover'] = $model->cover;
            if ($_FILES['Product']['error']['cover'] == 0) {
                $key = uniqid().'.jpg';
                $uploadMgr = new UploadManager();
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                $post['Product']['cover'] = 'http://'.Product::DOMAIN.'/'.$key;
                //---------应该有删除操作，删除qiniu中的图片
            }
            
            $pics = [];
            foreach($_FILES['Product']['tmp_name']['pics'] as $k => $file) {
                if ($_FILES['Product']['error']['pics'][$k] > 0) {
                    continue;
                }
                $key = uniqid().'.jpg';
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                $pics[$key] = 'http://'.Product::DOMAIN.'/'.$key;
            }
            $post['Product']['pics'] = json_encode(array_merge((array)json_decode($model->pics, true), $pics));
            if ($model->load($post) && $model->save()) {
                Yii::$app->session->setFlash('info', '修改成功');
            }
        }
        return $this->render('add', ['model' => $model, 'opts' => $list]);
    }

        //上架
    public function actionOn()
    {
        $productid= Yii::$app->request->get('productid');
        Product::updateAll(['ison'=>'1'],'productid=:id',[':id'=>$productid]);
        return $this->redirect(['product/list']);
        
    }
    
    public function actionOff()
    {
        $productid= Yii::$app->request->get('productid');
        if(Product::updateAll(['ison'=>'0'],'productid=:id',[':id'=>$productid])){
            return $this->redirect(['product/list']);
        }
    }
    public function actionDel()
    {
        $productid= Yii::$app->request->get('productid');
        Product::deleteAll('productid=:id',[':id'=>$productid]);
        return $this->redirect(['product/list']);
    }


    
    
    public function actionTest()
    {
        $auth=new \Qiniu\Auth(Product::AK, Product::SK);
        $opts=array(
            'callbackUrl'=>'http://www.callback.com/',
            'callbackBody'=>'name=$(fname)&hash=$(etag)'
        );
        $token=$auth->uploadToken(Product::BUCKET,null,3600,$opts);
        var_dump($token);
    }
    
    public function actionUploadtest()
    {
        $this->layout='adminlist.php';
        $model = new UploadForm();
    if (Yii::$app->request->isPost) {
        $model->file = UploadedFile::getInstance($model,'file');
//        if ($model->file && $model->validate()) {
//            Yii::$app->session->setFlash('info','上传成功');
//            $folder=date('Y/m/d',time());
////            var_dump(Yii::$app->basePath.'/web/uploadfile/');exit;
//            if(!file_exists(Yii::$app->basePath.'/web/uploadfile')){
//                mkdir(Yii::$app->basePath.'/web/uploadfile');
//            }
////            $model->file->saveAs('uploads/'.date('Y/m/d',time()).'/'.rand(000,999).'.'.$this->file->extension);
//            $model->file->saveas
//           // $model->file->saveAs(Yii::$app->basePath.'/web/uploadfile/',$model->file->baseName .'.'. $model->file->extension);
////            echo $model->file->baseName .'.'. $model->file->extension;
//        }else{
//            Yii::$app->session->setFlash('info','上传失败');
//        }
    }
    return $this->render('uploadtest', ['model' => $model]);
    }
    
    
    
    
}